package cn.wang.controller;

import cn.wang.auth.pojo.UserInfo;
import cn.wang.common.utils.CookieUtils;
import cn.wang.cart.config.JwtProperties;
import cn.wang.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class LoginController {

    @Autowired
    LoginService loginService;
    @Autowired
    JwtProperties jwtProperties;

    @PostMapping("login")
    public void register(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        // 通过service进行登录校验,如果成功返回token
        String token = loginService.login(username, password);
        // 将token设置到cookie中
        CookieUtils.setCookie(request, response,
                jwtProperties.getTokenName(), token,
                jwtProperties.getExpire() * 60);

    }

    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("ly_token") String token,
                                           HttpServletRequest request,
                                           HttpServletResponse response){
        UserInfo userInfo = loginService.verify(token);
        // 刷新token的存活时间
        String newToken = loginService.getToken(userInfo);
        // 刷新cookie的存活时间
        CookieUtils.setCookie(request,response,
                jwtProperties.getTokenName(),
                newToken,
                jwtProperties.getExpire()*60);
        return ResponseEntity.ok(userInfo);
    }
}
